const express = require('express')
const xlsx = require('xlsx')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath } = require('../utils/constants.js') // 引入常量

const router = express.Router()

// 使用绝对路径
const articlesFilePath = getFilePath('articles')
const usersFilePath = getFilePath('users')

// 获取文章详情路由（不需要身份验证）
router.get('/getArticleDetails', (req, res) => {
  const articleId = req.query.id
  // 读取文章文件
  const articlesWorkbook = xlsx.readFile(articlesFilePath)
  const articlesWorksheet = articlesWorkbook.Sheets['articles']
  const articlesData = xlsx.utils.sheet_to_json(articlesWorksheet)

  // 找到对应的文章
  const article = articlesData.find((item) => item.ID === articleId)

  // 如果文章不存在
  if (!article) {
    return sendResponse(res, 404, {}, '文章不存在。')
  }

  // 增加文章的阅读量
  article.ReadCount = (article.ReadCount || 0) + 1

  // 将更新后的文章数据写回 Excel
  const updatedArticlesData = articlesData.map((item) => {
    return item.ID === articleId ? article : item
  })
  const newArticlesSheet = xlsx.utils.json_to_sheet(updatedArticlesData)
  articlesWorkbook.Sheets['articles'] = newArticlesSheet
  xlsx.writeFile(articlesWorkbook, articlesFilePath)

  // 读取用户文件
  const usersWorkbook = xlsx.readFile(usersFilePath)
  const usersWorksheet = usersWorkbook.Sheets['users']
  const usersData = xlsx.utils.sheet_to_json(usersWorksheet)

  // 根据文章中的 AuthorID 找到作者信息
  const author = usersData.find((user) => user.ID === article.AuthorID)

  // 如果作者不存在
  if (!author) {
    return sendResponse(res, 404, {}, '作者信息未找到。')
  }

  // 返回文章详情和作者信息
  const articleDetails = {
    articleId: article.ID,
    title: article.Title,
    summary: article.Summary,
    content: article.Content,
    createdAt: article.CreatedAt,
    wordCount: article.WordCount,
    readCount: article.ReadCount, // 返回更新后的阅读量
    likeCount: article.LikeCount,
    author: {
      id: author.ID,
      nickname: author.Nickname,
      gender: author.Gender,
      phone: author.Phone,
      account: author.Account,
      followers: author.Followers, // 新增字段: 粉丝数
      totalWordsWritten: author.TotalWordsWritten, // 新增字段: 总共写的字数
      totalLikes: author.TotalLikes, // 新增字段: 总共获取的赞
      avatar: author.Avatar
    }
  }

  return sendResponse(res, 200, articleDetails, '文章详情获取成功。')
})

module.exports = router
